package main

import (
	"net"
	"strings"
)

type User struct {
	name   string
	addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

func NewUser(conn net.Conn, server *Server) *User {
	addr := conn.RemoteAddr().String()
	user := &User{
		name:   addr,
		addr:   addr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	go user.ListenMsg()
	return user
}

//用户上线
func (this *User) Online() {
	this.server.mapLock.Lock()
	this.server.OnlineMap[this.name] = this
	this.server.mapLock.Unlock()

	this.server.BroadCast(this, "上线了")
}

//用户下线
func (this *User) Offline() {
	this.server.mapLock.Lock()
	delete(this.server.OnlineMap, this.name)
	this.server.mapLock.Unlock()

	this.server.BroadCast(this, "下线了")
}

//用户发消息
func (this *User) DoMsg(msg string) {
	result := "当前在线的用户:\n"
	if msg == "who" {
		this.server.mapLock.Lock()
		for s, _ := range this.server.OnlineMap {
			result += s + "\n"
		}
		this.server.mapLock.Unlock()
		this.MsgToTargetUser(result)
	} else if len(msg) > 7 && msg[:7] == "rename=" {
		newName := strings.Split(msg, "=")[1]
		_, ok := this.server.OnlineMap[newName]
		if ok {
			this.MsgToTargetUser("昵称重复~")
		} else {
			this.server.mapLock.Lock()
			delete(this.server.OnlineMap, this.name)
			this.server.OnlineMap[newName] = this
			this.server.mapLock.Unlock()
			this.name = newName
			this.MsgToTargetUser("更名成功~,已更名为:" + newName + "\n")
		}
	} else if msg == "" {
		this.MsgToTargetUser("不能发送空消息~\n")
	} else {
		this.server.BroadCast(this, msg)
	}
}

//业务
func (this *User) MsgToTargetUser(msg string) {
	this.conn.Write([]byte(msg))
}

//用户监听消息
func (this *User) ListenMsg() {
	for {
		msg := <-this.C
		this.conn.Write([]byte(msg + "\n"))
	}
}
